package com.haoxuer.discover.user.rest.filters;

import com.haoxuer.discover.filter.common.Filter;
import com.haoxuer.discover.filter.common.FilterChain;
import com.haoxuer.discover.filter.common.HandlerRequest;
import com.haoxuer.discover.filter.common.HandlerResponse;
import com.haoxuer.discover.user.data.dao.UserOauthConfigDao;
import com.haoxuer.discover.user.oauth.api.OauthHandler;
import com.haoxuer.discover.user.oauth.domain.OauthResponse;
import com.haoxuer.discover.user.oauth.domain.TokenResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Scope("prototype")
@Component
public class ExtractOauthFilter implements Filter {

  @Autowired
  UserOauthConfigDao configDao;

  @Override
  public void doFilter(HandlerRequest request, HandlerResponse handlerResponse, FilterChain filterChain) {

    OauthHandler oauthHandler = configDao.id(request.getParameter("type"));
    if (oauthHandler == null) {
      handlerResponse.setCode(-1);
      handlerResponse.setMsg("该登陆方式无效");
      return ;
    }
    TokenResponse response = oauthHandler.getToken(request.getParameter("code"));
    if (response == null) {
      handlerResponse.setCode(-2);
      handlerResponse.setMsg("链接第三方失败");
      return ;
    }
    if (StringUtils.isEmpty(response.getOpenId())) {
      handlerResponse.setCode(-3);
      handlerResponse.setMsg("获取openid失败");
      return ;
    }
    request.setAttribute("response",response);

    OauthResponse oauthResponse = oauthHandler.login(response.getAccessToken(), response.getOpenId());
    request.setAttribute("oauthResponse",oauthResponse);

    filterChain.doFilter(request, handlerResponse);
  }
}
